//
//  ViewController.swift
//  leyihua
//
//  Created by xl12 on 2023/10/10.
//

import UIKit

class ViewController: BaseViewController {
    @IBOutlet var priceField: UITextField!
    
    @IBOutlet var hintLabel: UILabel!
    @IBOutlet var resultTextView: UITextView!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        priceField.keyboardType = .decimalPad
     }
    
    func convertToChineseNumber(_ number: Double) -> String? {
        let formatter = NumberFormatter()
        formatter.numberStyle = .spellOut
        formatter.locale = Locale(identifier: "zh_CN")
        
        guard let result = formatter.string(from: NSNumber(value: number)) else {
            return nil
        }
        return result
    }
    
    func valueToString(_ digit: Character) -> String {
        switch digit {
        case "〇":
            return "零"
        case "一":
            return "壹"
        case "二":
            return "贰"
        case "三":
            return "叁"
        case "四":
            return "肆"
        case "五":
            return "伍"
        case "六":
            return "陆"
        case "七":
            return "柒"
        case "八":
            return "捌"
        case "九":
            return "玖"
        case "十":
            return "拾"
        case "百":
            return "佰"
        case "千":
            return "仟"
        case "万":
            return "万"
        case "亿":
            return "亿"
        case "兆":
            return "万亿"
        case "元":
            return "元"
        case "角":
            return "角"
        case "分":
            return "分"
        default:
            return ""
        }
    }
    
    func convertToChinese(_ amount: Double) -> String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .spellOut
        formatter.locale = Locale(identifier: "zh_CN")
        
        let numberString = formatter.string(from: NSNumber(value: amount)) ?? ""
        var result = ""
        if (numberString.contains("点")) {
            // 分组
            let array = numberString.components(separatedBy: "点")
            if (array.count > 1) {
                var string = ""
                string += array[0]
                string += "元"
                var minStr = ""
                
                var index = 0
                for digit in array[1] {
                    let valid = String(digit)
                    minStr += valid
                    if (index == 0) {
                        minStr += "角"
                    }else if (index == 1) {
                        minStr += "分"
                    }
                    index += 1
                }
                string += minStr
                
                for digit in string {
                    result += valueToString(digit)
                }
            }
        }else {
            for digit in numberString {
                result += valueToString(digit)
            }
            result += "元整"
        }
//        self.resultTextView.text = result
        return result
    }
    
    @IBAction func shareAction(_ sender: Any) {
        DispatchQueue.main.async {
            let activityController = UIActivityViewController(activityItems: [self.resultTextView.text ?? ""], applicationActivities: nil)
            activityController.modalPresentationStyle = .fullScreen
            activityController.completionWithItemsHandler = {
                (type, flag, array, error) -> Void in
                if flag == true {
                    //                    分享成功
                } else {
                    //                    分享失败
                }
            }
            self.present(activityController, animated: true, completion: nil)
        }
    }
    
    
    @IBAction func convertAction(_ sender: Any) {
        let priceStr = priceField.text ?? ""
        if(priceStr.count == 0){
            let alertVC:UIAlertController = UIAlertController (title: "提示", message: "请输入小写金额", preferredStyle: .alert)
            let defaultAction = UIAlertAction(title: "确定", style: .default, handler: nil)
            alertVC.addAction(defaultAction)
            self.present(alertVC, animated: true, completion: nil)
        }
        if priceStr.contains(".") {
            let firstStr = priceStr.components(separatedBy: ".").first ?? ""
            if firstStr.count > 13 {
                let alertVC:UIAlertController = UIAlertController (title: "提示", message: "输入错误，最大只支持13位整数内容！", preferredStyle: .alert)
                let defaultAction = UIAlertAction(title: "确定", style: .default, handler: nil)
                alertVC.addAction(defaultAction)
                present(alertVC, animated: true, completion: nil)
                return
            }
        }
        
        
        if priceStr.count > 0 {
            if strFilter(priceStr) == true {
                let amount: Double = Double(priceStr) ?? 0
                let amountInChinese = convertToChinese(amount)
                print(amountInChinese)
                resultTextView.text = amountInChinese
//                resultTextView.isHidden = resultTextView.text.count != 0

            }else {
                let alertVC:UIAlertController = UIAlertController (title: "提示", message: "输入内容有误。请排查！", preferredStyle: .alert)
                let defaultAction = UIAlertAction(title: "确定", style: .default, handler: nil)
                alertVC.addAction(defaultAction)
                present(alertVC, animated: true, completion: nil)
                return
            }
        }
        let alertVC:UIAlertController = UIAlertController (title: "提示", message: "转换成功", preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "确定", style: .default, handler: nil)
        alertVC.addAction(defaultAction)
        self.present(alertVC, animated: true, completion: nil)
    }
    
    func strFilter(_ str: String) -> Bool {
        var isSure = false

        if isNumericString(str) == false {
            return isSure
        }
        
        switch str.filter({$0 == "."}).count {
        case 0, 1:
            isSure = true
        default:
            isSure = false
        }
        return isSure
    }
    
    func isNumericString(_ str: String) -> Bool {
        let regex = #"^[0-9.]+$"#
        let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
        return predicate.evaluate(with: str)
    }

    @IBAction func copyAction(_ sender: Any) {
        if resultTextView.text?.count ?? 0 > 0 {
            UIPasteboard.general.string = resultTextView.text
        }
        let alertVC:UIAlertController = UIAlertController (title: "提示", message: "复制成功", preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "确定", style: .default, handler: nil)
        alertVC.addAction(defaultAction)
        self.present(alertVC, animated: true, completion: nil)
    }
    
    @IBAction func resultAction(_ sender: Any) {
        convertAction(sender)
    }
    
    @IBAction func nextAction(_ sender: Any) {
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "HelpViewController")
        navigationController?.pushViewController(vc, animated: true)
    }
    
    
    @IBAction func userAction(_ sender: Any) {
        navigationController?.pushViewController(UserViewController(), animated: true)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
    
 
    
 }
 
